package com.gamecauca.screen;

import java.util.Random;

import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GLCommon;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Pool;
import com.gamecauca.Assets;
import com.gamecauca.Input;
import com.gamecauca.ItemDetails;
import com.gamecauca.World;
import com.gamecauca.animal.Fish;
import com.gamecauca.common.Constant;
import com.gamecauca.common.GameConfig;
import com.gamecauca.common.OverlapTester;


public class GameScreen extends Screen {
	static final int GAME_RUNNING = 1;
	static final int GAME_PAUSED = 2;
	static final int GAME_LEVEL_END = 3;
	static final int GAME_OVER = 4;
	
	private Screen parent;
	private int state;
	public static int totalMoney;
//	private int level;
	private OrthographicCamera guiCam;
	private Vector3 touchPoint;
	private SpriteBatch batcher;
	private World world;
	private Rectangle pauseBounds;
	private Rectangle resumeBounds;
	private Rectangle quitBounds;
	private int lastScore;
	private String scoreString;
	private static final int INIT_NUM_FISH = 5;
	private static final int MAX_NUM_FISH = 15;
	private static final float SCREEN_WIDTH = 320;
	private static final float SCREEN_HEIGHT = 480;
	
	public GameControl leftControl;
	public GameControl rightControl;
	public GameControl fishingControl;
	public GameControl attackControl;
	public GameControl marketControl;
	
	private int blood;// bien de cap nhat
	private int bloodInit;// ban dau
	public static int bloodPercent;// phan tram
	private int streng;
	private int strengInit;
	public static int strengPercent;
	private int time;
	private int timeInit;
	public static int timePercent;
	private int numOfUsingItem;
	private boolean isGameOver = false;
	private boolean isGameWin = false;
	private boolean isPassLevel = false;
	private int strengthCount = 0;
	
	private Rectangle itemBound;
	private int itemSelectId;
	public static int itemIndex;

	public GameScreen (Game game, Screen parent) {
		super(game);
		this.parent = parent;
		
		this.game.setNumSreen(Constant.GameScreen); 
		state = GAME_RUNNING;
		world = new World();
		guiCam = new OrthographicCamera(Constant.SCREEN_WIDTH,Constant.SCREEN_HEIGHT);
		guiCam.position.set(Constant.SCREEN_WIDTH/ 2, Constant.SCREEN_HEIGHT / 2, 0);
		touchPoint = new Vector3();
		batcher = new SpriteBatch();
		
		itemBound = new Rectangle();
		itemSelectId = -1;
		itemIndex = -1;
		
		leftControl = new GameControl( Assets.goToLeftRegion[0],0, 0);
		rightControl = new GameControl( Assets.goToRightRegion[1], 150, 0);
		fishingControl = new GameControl( Assets.catchHandRegion[0],560, 0);
		attackControl = new GameControl( Assets.attackRegion[0], 650, 0);
		marketControl = new GameControl( Assets.marketRegion, Constant.SCREEN_WIDTH-70,50+4*64);
		numOfUsingItem = 4;
		initilize();
	}
	public void initilize(){
//		level = 1;
//		totalMoney = Constant.MONEYINIT;// lay tong so tien ben market
		totalMoney = GameConfig.getPlayerMoney();// lay tong so tien ben market
//		bloodInit = Assets.bloodRegion.getRegionWidth();
		streng = world.getPlayerStreng();
		bloodInit = world.getPlayerBlood();
		bloodPercent = 10;
		blood = (bloodInit*bloodPercent)/100;
		strengInit = Assets.strengRegion.getRegionWidth();
		strengPercent = GameConfig.getPlayerStreng();
//		streng = (strengInit*strengPercent)/100;
//		timeInit = Assets.timerBarRegion.getRegionWidth();
		timeInit = GameConfig.getLevelTime();
		timePercent = 100;
		time = -1*Assets.timerBarRegion.getRegionWidth();
	}
	public void tick(Input input){// tuong tu ham update
//		System.out.println("======================= tick(Input input)  ne  ===============");
		switch (state) {
		case GAME_RUNNING:
//			System.out.println("go to MarketScreen class");
			updateRunning(input);
			break;
		case GAME_PAUSED:
			updatePaused(input);
			break;
		case GAME_LEVEL_END:
			updateLevelEnd(input);
			break;
		case GAME_OVER:
			updateGameOver(input);
			break;
		}
	}


	private void renderControl(){
		// neu nguoi dung dieu khien nguoi cau ca sang ben trai thi nut sang trai se duoc highlight
		leftControl = new GameControl( Assets.enabelLeft ? Assets.goToLeftRegion[1] : Assets.goToLeftRegion[0],0, 0);
		// neu nguoi dung dieu khien nguoi cau ca sang ben phai thi nut sang phai se duoc highlight
		rightControl = new GameControl( Assets.enabelRight ? Assets.goToRightRegion[0] : Assets.goToRightRegion[1], 150, 0);
		
		batcher.draw(leftControl.getTextureRegion(), leftControl.position.x,leftControl.position.y);
		batcher.draw(rightControl.getTextureRegion(), rightControl.position.x,rightControl.position.y);
		batcher.draw(fishingControl.getTextureRegion(), fishingControl.position.x,fishingControl.position.y);
		batcher.draw(attackControl.getTextureRegion(), attackControl.position.x,attackControl.position.y);
		batcher.draw(marketControl.getTextureRegion(), marketControl.position.x,marketControl.position.y,64,64);
	}
	// vẽ ra thanh công cụ
	private void renderUserItem(){
		for(int i =0;i<numOfUsingItem;i++){
			batcher.draw(Assets.container, Constant.SCREEN_WIDTH-70, 50+i*64);
		}
		for(int i =0;i<Assets.userBox.size();i++){
			ItemDetails item = Assets.userBox.get(i);
			int id = item.getId();
			batcher.draw(Assets.itemImgs[id], Constant.SCREEN_WIDTH-69, 242-i*64);
			Assets.font.draw(batcher,String.valueOf("x" + Assets.userBox.get(i).getQuantity()),Constant.SCREEN_WIDTH-70 + 15 , (242-i*64) + 40);
			
		}
	}
	// vẽ ra các thông số máu,sức mạnh,thời gian,số cá phải câu để qua màn...
	private void renderUserValues(){
		Assets.font.setColor(Color.BLUE);
		if(world!= null){
			Assets.font.draw(batcher, String.valueOf(world.getLevel()),34 , 439);
//			int kind = world.getFishToPassLevel();	
//			batcher.draw(Assets.fishRegionLeft[kind][0], 250, 410);	
//			Assets.font.draw(batcher,String.valueOf(world.getnumFishToPassLevel()),200 , 450);
			int fishWidthLevel = 0;
			
			
			for(int i = 0; i < world.getFishLevel().size(); i++){
				
				if(i > 0){
				
					Assets.font.draw(batcher,String.valueOf(world.getFishLevel().get(i).getFishAmountToPass() + "x"),
							fishWidthLevel, 430);
					
					batcher.draw(Assets.fishRegionLeft[world.getFishLevel().get(i).getKindFishToPass()][0], 
							fishWidthLevel + 60, 400);
					
					fishWidthLevel += 70 + Assets.fishRegionWidth[world.getFishLevel().get(i).getKindFishToPass()];
					
				}
				else{
					
					Assets.font.draw(batcher,String.valueOf(world.getFishLevel().get(i).getFishAmountToPass() + "x"),
							200 + 10, 430);
					
					batcher.draw(Assets.fishRegionLeft[world.getFishLevel().get(i).getKindFishToPass()][0], 
							200 + 60, 400);
					
					fishWidthLevel = 200 + 60 + (Assets.fishRegionWidth[world.getFishLevel().get(i).getKindFishToPass()]);
					
				}
				
				
			}
		}
		
		if(itemIndex >= 0){
			
			batcher.draw(Assets.itemImgs[itemSelectId], 450, 410);
		}
		
		StringBuffer buffer = new StringBuffer();
		buffer.append(totalMoney);
		buffer.append("  $");
		Assets.font.draw(batcher,buffer.toString(),550 , 460);
		
	}


	private void updateRunning (Input input) {
		if(input.buttons[Input.OPENDMARKET]){
			this.game.setScreen(new MarketScreen(game, this));
			return;
		}
		
		world.update(input);
		updateTimer();
		updateBlood();
		updateStreng();
		updateLevel();
		
		
	}
		

	private void updateLevel() {
		// TODO Auto-generated method stub
		if(timePercent<=0){// neu het thoi gian moi xet
			if(world!= null){
				
				boolean flg = false;
				
				for(int i = 0; i < world.getFishLevel().size(); i++){
					
					if(world.getFishLevel().get(i).getFishAmountToPass() == 0){
						flg = true;
					}
					else{
						flg = false;
						break;
					}
				}
				
				if(flg){
					
					timePercent = 100;// gan lai thoi gian
					state = GAME_LEVEL_END ;// dat dat--> qua level
				}
				else{
					isGameOver = true;//game over
				}
				
//				if(world.getnumFishToPassLevel()<=0){// so luong ca yeu cau da dat chua?
//					timePercent = 100;// gan lai thoi gian
//					state = GAME_LEVEL_END ;// dat dat--> qua level
//				}
//				else {
//					isGameOver = true;//game over
//				}
			}
		}
	}
	private void updatePaused (Input input) {
	}

	private void updateLevelEnd (Input input) {
//			System.out.println("updateLevelEnd ======================");
			world.setLevel(world.getLevel()+1);
			world.Initialize(world.getLevel());// init lai level moi
//			world.setnumFishToPassLevel(3);
//			world.setFishToPassLevel(world.getLevel()-1);
			isPassLevel = false;
			state = GAME_RUNNING;
	}

	private void updateGameOver (Input input) {
		if (Gdx.input.justTouched()) {
			game.setScreen(new MainMenuScreen(game));
		}
	}

	@Override
	public void present () {
		Gdx.input.setCatchBackKey(true);
		boolean isBackPressed = Gdx.input.isKeyPressed(com.badlogic.gdx.Input.Keys.BACK);
		if(isBackPressed){
			this.game.setScreen(new MainMenuScreen(game));
		}
		GLCommon gl = Gdx.gl;
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		gl.glEnable(GL10.GL_TEXTURE_2D);
		batcher.begin();
		
		world.render(batcher);
		
		
		//cai water nay em gan tam vao thui ngen
		batcher.end();

		guiCam.update();
		batcher.setProjectionMatrix(guiCam.combined);
		
		batcher.begin();
		batcher.draw(Assets.waterRegion,0,0,Constant.SCREEN_WIDTH,380);
		renderBackground();
		renderControl();
		renderUserItem();
		renderUserValues();
		batcher.end();
		
		switch (state) {
		case GAME_RUNNING:
			presentRunning();
			break;
		case GAME_PAUSED:
			presentPaused();
			break;
		case GAME_LEVEL_END:
			presentLevelEnd();
			break;
		case GAME_OVER:
			presentGameOver();
			break;
		}
	}

	private void presentRunning () {
		
		if (Gdx.input.justTouched()) {
			
			guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));
			
			for(int i =0;i<Assets.userBox.size();i++){
				
				itemBound.set(Constant.SCREEN_WIDTH-70, 50 + ((3 - i)*64), 64, 64);
				
				if(OverlapTester.pointInRectangle(itemBound, touchPoint.x, touchPoint.y)){
					
					this.setItemSelectId(Assets.userBox.get(i).getId());
					itemIndex = i;
				}
			}
			
		}
		
	}

	private void presentPaused () {
	}

	private void presentLevelEnd () {
		
	}

	private void presentGameOver () {
	}
	
	public void renderBackground () {
//		batcher.draw(Assets.backgroundRegion,0, 0, Constant.SCREEN_WIDTH,Constant.SCREEN_HEIGHT);
		batcher.draw(Assets.leftBarRegion,0, 400);
		batcher.draw(Assets.bloodRegion,93, 440,blood,Assets.bloodRegion.getRegionHeight());
		batcher.draw(Assets.strengRegion,93, 430,streng,Assets.strengRegion.getRegionHeight());
		batcher.draw(Assets.rightBarRegion,540, 390);
		batcher.draw(Assets.timerBarRegion,547+Assets.timerBarRegion.getRegionWidth(), 425,time,Assets.timerBarRegion.getRegionHeight());
		
	}

	@Override
	public void pause () {
		if (state == GAME_RUNNING) state = GAME_PAUSED;
	}

	@Override
	public void resume () {
		if (state == GAME_PAUSED) state = GAME_RUNNING;
	}

	@Override
	public void dispose () {
	}
	// cap nhat mau
	public void updateBlood(){
		
		if(bloodPercent > 100) bloodPercent = 100;
		if(bloodPercent <= 0) bloodPercent = 0;
		
		blood = (bloodInit * bloodPercent)/100;
	}
	// cap nhat streng
	public void updateStreng(){
		
		if(strengPercent > 100) strengPercent = 100;
		if(strengPercent <= 0)strengPercent = 0;
		
		if(strengthCount != world.getStrengthDown() && strengPercent > 0){
			strengPercent -= world.getStrengthDown();
			strengthCount = world.getStrengthDown();
		}

		streng = (strengInit*strengPercent)/100;
	}
	//cap nhat time
	public void updateTimer(){
		// neu 1 level mat 5 phut thi 1 phan tram tuong ung voi 
		// 169 vong paint
		//1 s co 56.48 vong paint
//		if(Game.timer %85 == 0)timePercent--;
		if(timePercent > 100) timePercent = 100;
		if(Game.timer %10 == 0)timePercent--;
		if(timePercent <=0)timePercent = 0;
		time = -1*(timeInit*timePercent)/100;
		
	}
	public void setItemSelectId(int itemSelectId) {
		this.itemSelectId = itemSelectId;
	}
	public int getItemSelectId() {
		return itemSelectId;
	}
	
}
